package Tools;

/**
 * **********PAGINA ENCARGADA DE COMPROBAR DATOS DE USUARIO*************
 */
import classes.AdminDB;
import classes.BaseServlet;
import classes.user;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Date;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

/**
 *
 * @author Alvaro
 */
@WebServlet(name = "login_process1", urlPatterns = {"/login_process1"})
public class login_process1 extends BaseServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, ClassNotFoundException {


        //Parametros enviados en el formulario
        String email = (request.getParameter("email") != null ? request.getParameter("email") : "");
        String pass = (request.getParameter("pass") != null ? request.getParameter("pass") : "");

        String remember = (request.getParameter("remember") != null ? request.getParameter("remember") : "");

        AdminDB adb = new AdminDB();

        //Comprobamos si se conecta el administrador para redirigirle a la consola de admin.
        if (email.equals("admin") && pass.equals("admin")) {
            System.out.println("El adminstrador ha accedido al sistema a las " + getTime());
            Cookie admin = new Cookie("admin", "admin");
            admin.setMaxAge(-1);
            response.addCookie(admin);
            response.sendRedirect("Admin/Admin.jsp");

        } //Comprobamos los datos introducidos por el usuario
        //Si los datos son correctos...
        else {
            if (adb.autentificar(email, pass)) {

                user u = new user();
                String name = u.recoverName(adb.getConnection(), email);
                System.out.println("El usuario " + email + " acaba de acceder al sistema");

                //comprobamos si el usuario que recordar sus datos
                if (remember.equals("on")) {
                    //Creamos cookies para la sesion del usuario
                    Cookie cookiename = new Cookie("name", name);
                    cookiename.setMaxAge(365 * 24 * 60 * 60);
                    response.addCookie(cookiename);

                    Cookie cookie = new Cookie("email", email);
                    cookie.setMaxAge(365 * 24 * 60 * 60);
                    response.addCookie(cookie);
                    System.out.println("Duracion de la cookie "+cookie.getName()+": "+cookie.getMaxAge());
                } else {
                    Cookie cookiename = new Cookie("name", name);
                    cookiename.setMaxAge(-1);
                    response.addCookie(cookiename);

                    Cookie cookie = new Cookie("email", email);
                    cookie.setMaxAge(-1);
                    response.addCookie(cookie);
                    System.out.println("Duracion de la cookie "+cookie.getName()+": "+cookie.getMaxAge());
                }



                //Redirigimos
                response.sendRedirect("index.jsp");


            } //Si los datos no son correctos...
            else {

                dispatch("/errorLogin.jsp", request, response);
            }
        }
    }

    private String getTime() {
        return new Date(System.currentTimeMillis()).toString();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(login_process1.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            Logger.getLogger(login_process1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(login_process1.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            Logger.getLogger(login_process1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
